<template>
    <div ref="scrollerRef" class="scroller">
        <div :class="{trans:hasTrans}" :style="{transform: `translateY(${scrollTranslate}px)`}">
            <slot></slot>
        </div>
    </div>
</template>
<script>
import { ref, onMounted } from 'vue'
export default {
    name: 'IosStyleScroller',
    setup() {
        const scrollerRef = ref(null)
        const hasTrans = ref(false)
        const scrollTranslate = ref(0)

        onMounted(()=>{
            initScroller()
        })

        function initScroller() {
            //初始化触摸回弹
            const scroller = scrollerRef.value
            const maxMove = 500;
            let startY = 0
            let startTransform = false;
            function touchMove(event){
                event.stopPropagation()
                // 阻尼系数0.3
                if (scroller.scrollTop == 0 || scroller.scrollHeight - scroller.clientHeight == scroller.scrollTop) {
                    const y = event.changedTouches[0].pageY - startY <= maxMove ? event.changedTouches[0].pageY - startY : maxMove;
                    if (startTransform) {
                        scrollTranslate.value = 0.3 * y
                    } else {
                        startTransform = true;
                        startY = event.changedTouches[0].pageY;
                    }

                }
            }

            function touchEnd(event){
                scroller.removeEventListener('touchmove', touchMove)
                scroller.removeEventListener('touchend', touchEnd)
                // 添加过渡效果
                hasTrans.value = true
                scrollTranslate.value = 0
                startTransform = false
            }

            scroller.addEventListener('touchstart', event => {
                hasTrans.value = false
                scroller.addEventListener('touchmove', touchMove);
                scroller.addEventListener('touchend', touchEnd);
            });
        }

        return {
            scrollerRef,
            scrollTranslate,
            hasTrans
        }
    }
}
</script>
<style lang="less" scoped>
.scroller {
    height: 100%;
    min-height: 100px;
    position: relative;
    overflow-y: auto;
    overscroll-behavior: contain;

    .trans {
        transition: transform .4s ease-out
    }
}
</style>